package com.beust.android.translate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONObject;

import android.util.Log;

public class ReverseGeoCoder {
	private static final String ENCODING = "UTF-8";
	//TODO: change URL reverse geocoding latitude  longitude
	private static final String URL_STRING = "http://maps.google.com/maps/geo?q=";
	
    
    /**
     * Translates text from a given language to another given language using Google Translate
     * latitude longitude
     * @param text The String to translate.
     * @param from The language code to translate from.
     * @param to The language code to translate to.
     * @return The translated String.
     * @throws MalformedURLException
     * @throws IOException
     */
    public static String GetCountry(float latitude, float longitude) throws Exception {
            return retrieveReverseGeoCode(latitude, longitude);
    }
    /**
     * Forms an HTTP request and parses the response for a reverse geocoding.
     *
     * @param text The String to translate.
     * @param from The language code to translate from.
     * @param to The language code to translate to.
     * @return The translated String.
     * @throws Exception
     */
    private static String retrieveReverseGeoCode(float latitude, float longitude) throws Exception {
        try {
            StringBuilder url = new StringBuilder();
            //TODO: add params to url
            url.append(URL_STRING).append(latitude).append(",").append(longitude);
            //url.append(TEXT_VAR).append(URLEncoder.encode(longitude, ENCODING));

            Log.d(TranslateService.TAG, "Connecting to " + url.toString());
            HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
            uc.setDoInput(true);
            uc.setDoOutput(true);
            try {
                Log.d(TranslateService.TAG, "getInputStream()");
                InputStream is= uc.getInputStream();
                String result = toString(is);
                
                JSONObject json = new JSONObject(result);
                String str = json.getJSONArray("Placemark").getJSONObject(1).getString("address").split(",")[1].trim().toString();
                return str;
            } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
                uc.getInputStream().close();
                if (uc.getErrorStream() != null) uc.getErrorStream().close();
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
	
	/**
     * Reads an InputStream and returns its contents as a String. Also effects rate control.
     * @param inputStream The InputStream to read from.
     * @return The contents of the InputStream as a String.
     * @throws Exception
     */
    private static String toString(InputStream inputStream) throws Exception {
        StringBuilder outputBuilder = new StringBuilder();
        try {
            String string;
            if (inputStream != null) {
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(inputStream, ENCODING));
                while (null != (string = reader.readLine())) {
                    outputBuilder.append(string).append('\n');
                }
            }
        } catch (Exception ex) {
            Log.e(TranslateService.TAG, "Error reading translation stream.", ex);
        }
        return outputBuilder.toString();
    }
}
